import { asyncRouterHandle } from '@/utils/asyncRouter'
import { emitter } from '@/utils/bus.js'
import { asyncMenu } from '@/api/menu'
import { defineStore } from 'pinia'
import { ref, watchEffect } from 'vue'
import { sortBySort } from '@/utils/format'

const formatRouter = (routes, routeMap, parent) => {
  routes &&
    routes.forEach((item) => {
      item.parent = parent
      //item.meta.btns = item.btns
      item.meta.hidden = item.hidden
      // if (item.meta.defaultMenu === true) {
      //   if (!parent) {
      //     item = { ...item, path: `/${item.path}` }
      //     notLayoutRouterArr.push(item)
      //   }
      // }
      routeMap[item.name] = item
      if (item.children && item.children.length > 0) {
        formatRouter(item.children, routeMap, item)
      }
    })
}

export const useRouterStore = defineStore('router', () => {
  const asyncRouterFlag = ref(0)
  const asyncRouters = ref([])
  const topMenu = ref([])
  const leftMenu = ref([])
  const menuMap = {}
  const topActive = ref('')
  const setLeftMenu = (name) => {
    localStorage.setItem('topActive', name)
    topActive.value = name
    if (menuMap[name]?.children.length > 0) {
      leftMenu.value = menuMap[name].children
    } else {
      leftMenu.value = []
    }
    return menuMap[name]?.children.length > 0
  }

  watchEffect(() => {
    let topActive = localStorage.getItem('topActive')
    let firstHasChildren = ''
    topMenu.value = []
    asyncRouters.value[0]?.children.forEach((item) => {
      if (item.hidden) return
      menuMap[item.name] = item
      if (!firstHasChildren && item.children && item.children.length > 0) {
        firstHasChildren = item.name
      }
      topMenu.value.push({ ...item, children: [] })
    })
    setLeftMenu(topActive)
  })

  const routeMap = {}
  // 从后台获取动态路由
  const SetAsyncRouter = async () => {
    asyncRouterFlag.value++
    const baseRouter = [
      {
        path: '/layout',
        name: 'layout',
        component: 'view/layout/index.vue',
        meta: {
          title: '底层layout'
        },
        children: []
      }
    ]
    const res = await asyncMenu()
    const asyncRouter = sortBySort(res.result)
    asyncRouter &&
      asyncRouter.push({
        path: 'reload',
        name: 'Reload',
        hidden: true,
        meta: {
          title: '',
          closeTab: true
        },
        component: 'view/error/reload.vue'
      })
    formatRouter(asyncRouter, routeMap)
    baseRouter[0].children = asyncRouter
    //定义非菜单跳转页面
    const jumpArr = [
      {
        path: 'myApp',
        name: 'myApp',
        meta: {
          path: 'view/dashboard/myApp.vue',
          hidden: true,
          title: '我的应用'
        },
        hidden: true,
        component: 'view/dashboard/myApp.vue'
      }
    ]
    baseRouter[0].children.push(...jumpArr)
    asyncRouterHandle(baseRouter)
    asyncRouters.value = baseRouter
    return true
  }
  return {
    topActive,
    setLeftMenu,
    topMenu,
    leftMenu,
    asyncRouters,
    asyncRouterFlag,
    SetAsyncRouter,
    routeMap
  }
})
